import {
    rankingStore
} from "../../store/ranking-store"
import {
    getBanners,
    getSongMenu
} from "../../service/api_music"
import queryRect from "../../utils/select-rect"
import throttle from "../../utils/throttle"
const throttleQueryRect = throttle(queryRect, 1000)
Page({
    data: {
        swiperHeight: 0,
        banners: [],
        playlists: [],
        recommendSongMenu: [],
        recomendSongs: [],
        rankings: {0:{},2:{},3:{}}
    },
    onLoad() {
        this.getBanners() // 获取轮播图
        // 发起共享数据的请求
        rankingStore.dispatch('getRanKingDateAction')
        rankingStore.onState('hotRanking', res => {
            if (!res.tracks) return
            const recomendSongs = res.tracks.slice(0, 6)
            this.setData({
                recomendSongs
            })
        })
        rankingStore.onState('newRanking', this.getNewRankingHander(0))
        rankingStore.onState('originRanking', this.getNewRankingHander(2))
        rankingStore.onState('upRanking', this.getNewRankingHander(3))
    },
    // 网络请求 页面加载
    getBanners() {
        getBanners({
            type: 2
        }).then(res => {
            this.setData({
                banners: res.banners
            })
        })
        getSongMenu().then(res => {
            this.setData({
                playlists: res.playlists
            })
        })
        getSongMenu("华语").then(res => {
            this.setData({
                recommendSongMenu: res.playlists
            })
        })
    },
    // 点击了Search框
    handleSearchClick() {
        wx.navigateTo({
            url: '/pages/detail-search/index',
        })
    },
    //图片加载完成后
    handleSwiperImageLoaded() {
        // 获取组件/图片高度
        throttleQueryRect('.swiper-image').then(res => {
            const rect = res[0]
            this.setData({
                swiperHeight: rect.height
            })
        })
    },
    // 推荐歌曲点击
    handersong(event) {
        const {
            name,
            id
        } = event.currentTarget.dataset.item
        console.log(name, id)
    },
    onUnload() {
        // rankingStore.offState('newRanking',this.getNewRankingHander
    },
    getNewRankingHander(idx) {
        return (res) => {   //这里使用了闭包 访问了 idx变量
            if (Object.keys(res).length === 0) return
            const name = res.name
            const coverImgUrl = res.coverImgUrl
            const playCount = res.playCount
            const songList = res.tracks.slice(0, 3)
            const rankingObj = {
                name,
                coverImgUrl,
                playCount,
                songList
            }
            // 动态映射+覆盖
            // const newRanKings = this.data.rankings[idx] = rankingObj
            const newRanKings = {...this.data.rankings,[idx]:rankingObj}
            console.log('newRanKings',newRanKings)
            this.setData({
                rankings: newRanKings
            })
        }
    }
})